package com.sy.servlet;

import com.sy.entity.User;
import com.sy.service.UserService;
import com.sy.service.impl.UserServiceImpl;
import com.sy.vo.LoginParams;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

import static com.sy.constant.BusinessConstant.AUTO_LOGIN;
import static com.sy.constant.BusinessConstant.COOKIE_USER_NAME;
import static com.sy.constant.BusinessConstant.COOKIE_USER_NAME_MAX_AGE;
import static com.sy.constant.BusinessConstant.SESSION_CODE;
import static com.sy.constant.BusinessConstant.SESSION_USER;

@WebServlet("/users/*")
public class UserServlet extends AbstractBaseServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected Object doService(String action, HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
        //注册
        if ("regist".equals(action)) {
            userService.regist(req.getParameter("userName"), req.getParameter("userPwd"), req.getParameter("userPwdConfirm"));
        }
        //登录
        if ("login".equals(action)) {
            LoginParams loginParams = paramMap2Bean(req, LoginParams.class);
            //当前登录成功后对应的用户信息
            User user = userService.login(loginParams, getSessionAttribute(req, SESSION_CODE));
            //如果是自动登录操作，则需要把用户信息写入Cookie中
            if (AUTO_LOGIN.equals(loginParams.getAutoLogin())) {
                setCookie(res, COOKIE_USER_NAME, DigestUtils.md5Hex(user.getName() + "," + user.getPwd()), COOKIE_USER_NAME_MAX_AGE);
            }
            //对密码脱敏
            user.setPwd(null);
            //将密码存入Session中
            setSessionAttribute(req, SESSION_USER, user);
            return user;
        }
        //获取登录后的用户信息
        if ("loginUser".equals(action)) {
            User user = getSessionAttribute(req, SESSION_USER);
            if (Objects.isNull(user)) {
                throw new RuntimeException("用户尚未登录");
            }
            return user;
        }
        //自动登录操作
        if ("autoLogin".equals(action)) {
            String cookieUserInfo = getCookie(req, COOKIE_USER_NAME);
            //将Cookie中的用户信息交给Service处理，看是否能够完成自动登录
            //如果可以在返回用户信息并在Session中设置用户信息
            User user = userService.autoLogin(cookieUserInfo);
            if (Objects.nonNull(user)) {
                //密码脱敏
                user.setPwd(null);
                setSessionAttribute(req, COOKIE_USER_NAME, user);
            }
            return user;
        }
        return null;
    }
}
